package com.kiln.juxingqs.ui

import android.content.Context
import android.os.Build
import android.view.View
import androidx.annotation.RequiresApi
import client.global.commlib.widget.EmptyLayout
import com.kiln.juxingqs.R
import com.kiln.juxingqs.databinding.ActivityWebBinding
import com.kiln.juxingqs.ui.vm.WebViewModel
import com.kiln.juxingqs.BaseMiddleActivity
import com.kiln.juxingqs.databinding.ActivityWebPayBinding
import android.content.Intent
import android.net.Uri
import android.webkit.*
import java.lang.Exception
import android.content.pm.PackageInfo

import android.content.pm.PackageManager
import client.global.commlib.toast.toast


class WebPayActivity : BaseMiddleActivity<WebViewModel, ActivityWebPayBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_web_pay
    }

    var title: String? = ""
    var url: String? = ""
    override fun initViewModel(): WebViewModel = createViewModel()

    override fun initView() {
        binding.event = this
        url = intent.getStringExtra("adInfo")
        title = intent.getStringExtra("title")
        binding.title = (title)


        val mWebSettings = binding.wvShow.settings
        mWebSettings.setJavaScriptEnabled(true)
        mWebSettings.setBuiltInZoomControls(false)
        mWebSettings.setLightTouchEnabled(true)
        // 使用localStorage则必须打开
        mWebSettings.setDomStorageEnabled(true)
        mWebSettings.setSupportZoom(false)

//        // 设置可以访问文件
//        mWebSettings.setAllowFileAccess(true);
//        // 设置支持缩放
//        mWebSettings.setBuiltInZoomControls(true);
//        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        mWebSettings.setGeolocationEnabled(true);

        binding.wvShow.isHapticFeedbackEnabled = false
        url?.let {
            binding.wvShow.loadUrl(url!!)
        }
        binding.wvShow.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {

                try {
                    if (url!!.startsWith("weixin://")
                        || url!!.startsWith("alipays://")
                        || url!!.startsWith("bestpay://")
                    ) {

//                        if (url!!.startsWith("weixin://")) {
//                            if (!isWeixinAvilible(this@WebPayActivity)) {
//                                toast("请安装微信")
//                                return true
//                            }
//                        }
//
//                        if (url!!.startsWith("alipays://")) {
//                            if (!checkAliPayInstalled(this@WebPayActivity)) {
//                                toast("请安装支付宝")
//                                return true
//                            }
//                        }

                        val intent = Intent()
                        intent.action = Intent.ACTION_VIEW
                        intent.data = Uri.parse(url)
                        startActivity(intent)
                        return true
                    }
                } catch (e: Exception) {
                    return false
                }
                url?.let {
                    view.loadUrl(url)
                }

//                if (parseScheme(url)) {
//                    try {
//                        if (url!!.startsWith("weixin://") || url!!.startsWith("alipays://") || url!!.startsWith(
//                                "bestpay://"
//                            )
//                        ) {
//                            val intent = Intent()
//                            intent.action = Intent.ACTION_VIEW
//                            intent.data = Uri.parse(url)
//                            startActivity(intent)
//                            return true
//                        }
//                    } catch (e: Exception) {
//                        return false
//                    }
//
//                    url?.let {
//                        view.loadUrl(url)
//                    }
//
//                } else {
//                    url?.let {
//                        view.loadUrl(url)
//                    }
//                }

                return true
            }

            @RequiresApi(Build.VERSION_CODES.KITKAT)
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                binding.emptyLayout.visibility = View.GONE
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR

            }
        })
        binding.wvShow.addJavascriptInterface(this, "android")

    }

//    private fun parseScheme(url: String?): Boolean {
//        if (url!!.contains("platformapi/startapp")){
//            myHandler.removeCallbacks(runable);
//            return true;
//        } else if(url.contains("web-other")){
//
//            myHandler.postDelayed(runable, 10000);
//            return false;
//        }else {
//            return false;
//        }
//    }


    override fun onDestroy() {
        binding.wvShow.stopLoading()
        binding.wvShow.clearHistory()
        binding.wvShow.clearCache(true)
        binding.wvShow.removeAllViews()
        binding.wvShow.destroy()
        super.onDestroy()
    }

    //判断是否安装了微信
    fun isWeixinAvilible(context: Context): Boolean {
        val packageManager = context.packageManager
        val pinfo = packageManager.getInstalledPackages(0)
        if (pinfo != null) {
            for (i in pinfo.indices) {
                val pn = pinfo[i].packageName
                if (pn == "com.tencent.mm") {
                    return true
                }
            }
        }
        return false
    }

    //判断是否安装支付宝app
    fun checkAliPayInstalled(context: Context): Boolean {
        val uri = Uri.parse("alipays://platformapi/startapp")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        val componentName = intent.resolveActivity(context.getPackageManager())
        return componentName != null
    }

    @JavascriptInterface
    fun backCall() {
        finish()
    }
}